package cn.usian.service.impl;

import cn.usian.common.R;
import cn.usian.dao.SetmealDishMapper;
import cn.usian.dao.SetmealMapper;
import cn.usian.entity.DtoSetmeal;
import cn.usian.entity.Setmeal;
import cn.usian.entity.SetmealDish;
import cn.usian.exception.NameException;
import cn.usian.service.SetmealService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class SetmealServiceImpl implements SetmealService {
    @Resource
    private SetmealMapper setmealMapper;

    @Resource
    private SetmealDishMapper setmealDishMapper;

    @Override
    public R<Page> page(int page, int pageSize, String name) {
        /*LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(name != null, Setmeal::getName, name);*/
        Page<DtoSetmeal> page1 = new Page<>(page, 10);
        Page<DtoSetmeal> setmealPage = setmealMapper.findPage(page1, name);
        return R.success(setmealPage);
    }

    @Override
    public R status(Integer status, long[] ids) {
        Setmeal setmeal = new Setmeal();
        for (long id : ids) {
            setmeal.setId(id);
            setmeal.setStatus(status);
            setmealMapper.updateById(setmeal);
        }
        return R.success("修改成功");
    }

    @Override
    public R delete(Long[] ids) {
        Setmeal setmeal = new Setmeal();
        for (Long id : ids) {
            setmeal.setId(id);
            setmeal.setIsDeleted(1);
            setmealMapper.updateById(setmeal);
        }
        return R.success("删除成功");
    }

    @Override
    public void add(DtoSetmeal setmealDto) {
        //判断姓名是否存在
        if (findByName(setmealDto.getName())!=null){
            throw new NameException(setmealDto.getName());
        }

        setmealMapper.insert(setmealDto);

        List<SetmealDish> setmealDishList = setmealDto.getSetmealDishes();


        for (SetmealDish setmealDish : setmealDishList) {
            setmealDish.setSetmealId(setmealDto.getId());
            setmealDish.setCreateTime(setmealDto.getCreateTime());
            setmealDish.setUpdateTime(setmealDto.getCreateTime());
            setmealDish.setCreateUser(setmealDto.getCreateUser());
            setmealDish.setUpdateUser(setmealDto.getUpdateUser());
        }
        for (SetmealDish setmealDish : setmealDishList) {
            setmealDishMapper.insert(setmealDish);
        }
    }

    public Setmeal findByName(String name) {
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(name!=null,Setmeal::getName,name);
        return setmealMapper.selectOne(queryWrapper);
    }
}
